package com.allen.retrofit2_rxjava2.view.selectimageview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.allen.retrofit2_rxjava2.R;
import com.allen.retrofit2_rxjava2.base.TitleViewActivity;
import com.allen.retrofit2_rxjava2.utils.ToastUtils;
import com.allen.retrofit2_rxjava2.view.selectimageview.adapter.PhotoGridAdapter;
import com.allen.retrofit2_rxjava2.view.selectimageview.adapter.PhotoListAdapter;
import com.allen.retrofit2_rxjava2.view.selectimageview.entity.AlbumInfo;
import com.allen.retrofit2_rxjava2.view.selectimageview.entity.PhotoInfo;
import com.allen.retrofit2_rxjava2.view.selectimageview.utils.CameraUtil;
import com.allen.retrofit2_rxjava2.view.selectimageview.utils.CheckImageLoaderConfiguration;
import com.allen.retrofit2_rxjava2.view.selectimageview.utils.ThumbnailsUtil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

public class PhotoActivity extends TitleViewActivity {
    @BindView(R.id.photo_ablum_name)
    TextView ablumName;
    @BindView(R.id.main_botton_menu)
    LinearLayout bottomMenu;
    @BindView(R.id.main_gridview)
    GridView gridView;
    @BindView(R.id.photo_ablum_name_shade)
    ImageView shade;// 一个半透明的遮罩

    public static int CAMERA_REQUEST_CODE_TO = 4;

    String[] requestPermissions = new String[]{Manifest.permission.INTERNET, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};

    @Override
    public void init() {
        setContentView(R.layout.activity_photo);
        //inflate()方式加载布局,只能加载一次
        cr = getContentResolver();
        initTitleBar();
        checkPermission();
        initPopWindow();
        initListView();
        // new ImageAsyncTask().execute();
        if (PermissionChecker.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            new ImageAsyncTask().execute();
        }
    }

    @Override
    public void data() {

    }

    @Override
    public void listener() {
        super.listener();
//        tv_double_click.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showToast("防止重复点击响应的click/可对实践拦截");
//            }
//        });
//        getWindow().getDecorView().post(new Runnable() {
//            @Override
//            public void run() {
//                HookViewClickUtil.hookView(tv_double_click);
//            }
//        });
    }


    @OnClick({R.id.main_botton_menu})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_botton_menu:
                shade.setVisibility(View.VISIBLE);
                mPopupWindow.showAtLocation(ablumName, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
                        bottomMenu.getHeight());
                break;
            default:
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        CheckImageLoaderConfiguration.checkImageLoaderConfiguration(this);
    }

    // private final static int REQEST_CODE_CAMERA = 100; // 拍照
    // private final static int REQEST_CODE_ALBUM = 101; // 相册
    private final static int REQEST_CODE_CROP = 102; // 剪裁
    private final static int REQEST_CODE_CROP_RESULT = 103;// 剪裁结果
    private ContentResolver cr;


    private List<AlbumInfo> listImageInfo = new ArrayList<AlbumInfo>();// 相册集合
    private PhotoListAdapter listAdapter;
    private PhotoGridAdapter gridAdapter;

    private class ImageAsyncTask extends AsyncTask<Void, Void, Object> {
        @Override
        protected Object doInBackground(Void... params) {
            // 获取缩略图
            ThumbnailsUtil.clear();
            String[] projection = {BaseColumns._ID, Thumbnails.IMAGE_ID, Thumbnails.DATA};
            Cursor cur = cr.query(Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, null);

            if (cur != null && cur.moveToFirst()) {
                int image_id;
                String image_path;
                int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID);
                int dataColumn = cur.getColumnIndex(Thumbnails.DATA);
                do {
                    image_id = cur.getInt(image_idColumn);
                    image_path = cur.getString(dataColumn);
                    ThumbnailsUtil.put(image_id, "file://" + image_path);
                } while (cur.moveToNext());
            }
            // 获取原图
            Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    "date_modified DESC");
            String _path = "_data";
            String _album = "bucket_display_name";
            HashMap<String, AlbumInfo> myhash = new HashMap<String, AlbumInfo>();
            AlbumInfo albumInfo = null;
            PhotoInfo photoInfo = null;
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    int index = 0;
                    int _id = cursor.getInt(cursor.getColumnIndex("_id"));
                    String path = cursor.getString(cursor.getColumnIndex(_path));
                    String album = cursor.getString(cursor.getColumnIndex(_album));
                    List<PhotoInfo> stringList = new ArrayList<PhotoInfo>();
                    photoInfo = new PhotoInfo();
                    if (myhash.containsKey(album)) {
                        albumInfo = myhash.remove(album);
                        if (listImageInfo.contains(albumInfo))
                            index = listImageInfo.indexOf(albumInfo);
                        photoInfo.setImage_id(_id);
                        photoInfo.setPath_file("file://" + path);
                        photoInfo.setPath_absolute(path);
                        albumInfo.getList().add(photoInfo);
                        listImageInfo.set(index, albumInfo);
                        myhash.put(album, albumInfo);
                    } else {
                        albumInfo = new AlbumInfo();
                        stringList.clear();
                        photoInfo.setImage_id(_id);
                        photoInfo.setPath_file("file://" + path);
                        photoInfo.setPath_absolute(path);
                        stringList.add(photoInfo);
                        albumInfo.setImage_id(_id);
                        albumInfo.setPath_file("file://" + path);
                        albumInfo.setPath_absolute(path);
                        albumInfo.setName_album(album);
                        albumInfo.setList(stringList);
                        listImageInfo.add(albumInfo);
                        myhash.put(album, albumInfo);
                    }
                } while (cursor.moveToNext());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);

            listAdapter = new PhotoListAdapter(getBaseContext(), listImageInfo);
            listview.setAdapter(listAdapter);
            if (null == listImageInfo || 0 == listImageInfo.size()) {
                return;
            }

            ablumName.setText(listImageInfo.get(0).getName_album());
            gridAdapter = new PhotoGridAdapter(getBaseContext(), listImageInfo.get(0).getList(), getWindowWith());
            gridView.setAdapter(gridAdapter);
            gridView.setOnItemClickListener(new MyGridOnItemListener(0));
            listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long paramLong) {
                    gridAdapter = new PhotoGridAdapter(getBaseContext(), listImageInfo.get(paramInt).getList(),
                            getWindowWith());
                    gridView.setAdapter(gridAdapter);
                    gridView.setOnItemClickListener(new MyGridOnItemListener(paramInt));
                    ablumName.setText(listImageInfo.get(paramInt).getName_album());
                    mPopupWindow.dismiss();
                }
            });
        }
    }

    private ListView listview;
    public static Bitmap bimap;

    private void initListView() {
        listview = (ListView) popView.findViewById(R.id.main_listview);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) listview.getLayoutParams();
        params.height = getWindowHeight() * 2 / 3;
        listview.setLayoutParams(params);
    }

    class MyGridOnItemListener implements OnItemClickListener {
        int paramInt;

        MyGridOnItemListener(int paramInt) {
            this.paramInt = paramInt;
        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            intent = new Intent(PhotoActivity.this, CropImageActivity.class);
            bundle = new Bundle();
            intent.putExtra("PATH", listImageInfo.get(paramInt).getList().get(arg2).getPath_file());
            startActivityForResult(intent, REQEST_CODE_CROP_RESULT);
        }
    }

    private PopupWindow mPopupWindow;
    private View popView;

    @SuppressLint("InflateParams")
    private void initPopWindow() {
        popView = LayoutInflater.from(this).inflate(R.layout.layout_photo_pop, null);
        mPopupWindow = new PopupWindow(popView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#E9E9E9")));
        // mPopupWindow.setAnimationStyle(R.style.popAnimation);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.update();
        mPopupWindow.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                shade.setVisibility(View.GONE);
            }
        });
    }

    private void initTitleBar() {
        initTitleView();
        initLeftBackView(null);
        setCenterViewContent(getResources().getString(R.string.photo));
        initRightView(getResources().getString(R.string.camera));
        setRightViewOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                /*
                 * startActivityForResult(CameraUtil.getCameraIntent(), REQEST_CODE_CROP);
                 */
                if (Build.VERSION.SDK_INT >= 23) {
                    // 判断是否有相机权限（主要用于兼容Android 6.0+）
                    if (ContextCompat.checkSelfPermission(PhotoActivity.this,
                            Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {// 有相机权限
                        startActivityForResult(CameraUtil.getCameraIntent(PhotoActivity.this), REQEST_CODE_CROP);
                    } else {
                        ActivityCompat.requestPermissions(PhotoActivity.this,
                                new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE_TO);// 无权限，申请相机权限，然后利用回调函数判断是否申请成功
                    }
                } else {
                    if (ContextCompat.checkSelfPermission(PhotoActivity.this,
                            Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        startActivityForResult(CameraUtil.getCameraIntent(), REQEST_CODE_CROP);
                    }
                }
            }
        });
    }

    public Intent intent;
    String filename;

    Bundle bundle;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQEST_CODE_CROP:// 拍照
                if (resultCode == RESULT_OK) {
                    filename = CameraUtil.getRealFilePath();
                    Intent intent = new Intent(this, CropImageActivity.class);
                    intent.putExtra("PATH", "file://" + filename);
                    startActivityForResult(intent, REQEST_CODE_CROP_RESULT);
                }
                break;
            case REQEST_CODE_CROP_RESULT:// 剪裁结果
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK);
                    finish();
                }
                break;
            default:
                break;
        }
    }

    @SuppressLint("Override")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {// 申请权限后的回调操作
        // 判断请求码
        if (requestCode == CAMERA_REQUEST_CODE_TO) {
            // grantResults授权结果
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startActivityForResult(CameraUtil.getCameraIntent(PhotoActivity.this), REQEST_CODE_CROP);
            } else {
                // 授权失败
                ToastUtils.showToast(getResources().getString(R.string.camera_forbidden));
            }
        }

        if (requestCode == 10010) {
            if (null != permissions && permissions.length != 0 && permissions.length != requestPermissions.length) {
                //说明权限为全部允许
                ActivityCompat.requestPermissions(this, permissions, 10010);
            } else {
                //以允许全部权限
                //TimeUtils.getInstance().countDownUtils(3, listener);

            }
        }
    }


    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean needGrantedPermissions = false;
            for (int i = 0, size = requestPermissions.length; i < size; i++) {
                if (ActivityCompat.checkSelfPermission(this, requestPermissions[i])
                        != PackageManager.PERMISSION_GRANTED) {
                    needGrantedPermissions = true;
                } else {
                    requestPermissions[i] = "";
                }
            }
            if (needGrantedPermissions) {
                ActivityCompat.requestPermissions(this, requestPermissions, 10010);
            }
        }
    }

}
